package controller

import (
	"accountInfoServer/service"
	"encoding/json"
	"net/http"
)

// UserController 处理用户相关的HTTP请求
type UserController struct {
	userService service.UserService // 持有服务层实例
}

// NewUserController 创建UserController实例
func NewUserController(userService service.UserService) *UserController {
	return &UserController{
		userService: userService,
	}
}

// IndexHandler 处理根路径请求
func (c *UserController) IndexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	// 获取wps_sid cookie
	cookie, err := r.Cookie("wps_sid")
	if err != nil || cookie.Value == "" {
		loginURL := "https://account.wps.cn/?cb=https%3A%2F%2Finfo.wps.cn"
		http.Redirect(w, r, loginURL, http.StatusFound)
		return
	}

	// 调用服务层检查登录状态（核心修正：正确调用方法）
	loginStatus, err := c.userService.CheckLoginStatus(cookie.Value)
	if err != nil || loginStatus.Result != "ok" {
		loginURL := "https://account.wps.cn/?cb=https%3A%2F%2Finfo.wps.cn"
		http.Redirect(w, r, loginURL, http.StatusFound)
		return
	}

	// 已登录，跳转到用户信息接口
	http.Redirect(w, r, "/api/myinfo", http.StatusFound)
}

// MyInfoHandler 处理用户信息请求
func (c *UserController) MyInfoHandler(w http.ResponseWriter, r *http.Request) {
	// 获取wps_sid cookie
	cookie, err := r.Cookie("wps_sid")
	if err != nil || cookie.Value == "" {
		w.WriteHeader(http.StatusUnauthorized)
		json.NewEncoder(w).Encode(map[string]string{"error": "未登录或会话已失效"})
		return
	}
	wpsSid := cookie.Value

	// 调用服务层检查登录状态（核心修正：正确调用方法）
	loginStatus, err := c.userService.CheckLoginStatus(wpsSid)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]string{"error": "检查登录状态失败: " + err.Error()})
		return
	}
	if loginStatus.Result != "ok" {
		w.WriteHeader(http.StatusUnauthorized)
		json.NewEncoder(w).Encode(map[string]string{"error": "登录状态异常: " + loginStatus.Result})
		return
	}

	// 调用服务层获取用户信息（核心修正：正确调用方法）
	userInfo, err := c.userService.GetUserInfo(wpsSid, loginStatus.UserID)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]string{"error": "获取用户信息失败: " + err.Error()})
		return
	}

	// 返回用户信息
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(userInfo)
}
